package com.board.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.board.dto.StoreDto;
import com.board.dto.StoreInfoDto;
import com.board.entity.StoreInfo;
import com.board.exception.StoreException;
import com.board.mapper.StoreInfoMapper;
import com.board.param.*;
import com.board.service.StoreInfoService;
import com.board.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LGL
 * @since 2024年04月03日
 */
@Service
public class StoreInfoServiceImpl extends ServiceImpl<StoreInfoMapper, StoreInfo> implements StoreInfoService {
    @Autowired
    private StoreInfoMapper storeInfoMapper;

    @Override
    public StoreDto findStoreById(Integer storeId) {
        StoreInfo storeInfo = storeInfoMapper.selectById(storeId);
        if (storeInfo==null) throw new StoreException(500,"没有该商家");
        StoreDto dto = BeanUtil.toBean(storeInfo, StoreDto.class);
        return dto;
    }

    @Override
    public StoreInfoDto login(StoreLoginParam param) {

        // 根据登录账号查询商家信息
        LambdaQueryWrapper<StoreInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StoreInfo::getStoreLoginAccount, param.getStoreLoginAccount());
        StoreInfo storeInfo = storeInfoMapper.selectOne(wrapper);

        // 如果商家信息不存在，则抛出账号或密码错误异常
        if (storeInfo == null) {
            throw new StoreException(10006, "账号不存在");
        }

        // 验证密码是否正确，不正确则抛出账号或密码错误异常
        if (!storeInfo.getStorePass().equals(MD5Util.md5(param.getStoreLoginAccount(), param.getStorePass()))) {
            throw new StoreException(10007, "账号或密码错误");
        }

        // 检查商家账号状态，如果被禁用，则抛出账号状态异常异常
        if (storeInfo.getStoreState() == StateDate.STORE_STATE_Disabled) {
            throw new StoreException(10008, "账号状态异常");
        }
        StoreInfoDto storeInfoDto = BeanUtil.toBean(storeInfo, StoreInfoDto.class);

        return storeInfoDto;
    }
}
